# -*- coding:utf-8 -*-

import json

from channels.generic.websocket import AsyncWebsocketConsumer
import logging

logger = logging.getLogger("django")


class AsyncChatConsumer(AsyncWebsocketConsumer):
    def __init__(self, *args, **kwargs):
        super().__init__(args, kwargs)
        # 房间号，
        self.room = None
        # 将通过房间号进入的人，放到一个组里面
        self.room_group = None

    async def connect(self):
        self.room = self.scope["url_route"]["kwargs"].get("pk")
        self.room_group = f"chat_{self.room}"

        # Join room group
        await self.channel_layer.group_add(self.room_group, self.channel_name)

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(self.room_group, self.channel_name)

    # Receive message from WebSocket
    async def receive(self, text_data):
        # logger.info(text_data)
        # text_data_json = json.loads(text_data)
        # message = text_data_json["message"]
        message = text_data

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group, {"type": "chat.message", "message": message}
        )

    # Receive message from room group
    async def chat_message(self, event):
        message = event["message"]

        # Send message to WebSocket
        await self.send(text_data=json.dumps({"message": message}))

# from channels.layers import get_channel_layer
# import asyncio
#
# channel_layer = get_channel_layer()
#
# async def send_msg(user_id, text):
#     await channel_layer.group_send(user_id, {"type": "chat.message", "message": text})
#
# asyncio.run(send_msg("chat_12121212", "hello"))




